package sjtu.ist.warehouse4ws.dao;

import java.util.List;

import org.hibernate.Query;

import sjtu.ist.warehouse4ws.model.Oplog;
import sjtu.ist.warehouse4ws.model.Privilege;
import sjtu.ist.warehouse4ws.tool.ListPage;

public class OplogDaoHibernate extends BaseDaoHibernate implements OplogDao{

	@Override
	public Oplog get(String id) {
		return (Oplog)getHibernateTemplate().get(Oplog.class, id);
	}

	@Override
	public void save(Oplog oplog) {
		getHibernateTemplate().save(oplog);
	}

	@Override
	public void update(Oplog oplog) {
		getHibernateTemplate().update(oplog);
		
	}

	@Override
	public void delete(String id) {
		getHibernateTemplate().delete(get(id));
		
	}

	@Override
	public void delete(Oplog oplog) {
		getHibernateTemplate().delete(oplog);
		
	}

	@Override
	public ListPage getAllOplogs(int start,int limit) {
		Query query=getSession().createQuery("from Oplog");
		query.setFirstResult(start);//定义从第几条开始查询   
        query.setMaxResults(limit);//定义返回的记录数
        List<Privilege> list=query.list();
        
        long totalCount = ((Long) getHibernateTemplate().find("select COUNT(*) from Oplog").get(0)).longValue(); 
        ListPage pl=new ListPage(list,(int)totalCount);
		//return (List<Privilege>)getHibernateTemplate().find(hql);
        return pl;
	}

	@Override
	public ListPage searchOplog(String user,
			String after, String before, String file, String operation,
			String dspt,int start,int limit) {
		// TODO Auto-generated method stub
		String select="select o ";
		String hql="from Oplog AS o ";
		boolean finduser=false;
		boolean findfile=false;
		if(user!=null && !user.equalsIgnoreCase("")){
			finduser=true;
			hql=hql.concat(",User AS u ");
		}
		if(file!=null && !file.equalsIgnoreCase("")){
			findfile=true;
			hql=hql.concat(",Fileinfo AS f ");
		}
		hql=hql.concat("where 1=1 ");
		if(finduser){
			hql+="and u.id = o.user and u.name like '%"+user+"%' ";
		}
		if(findfile){
			hql+="and f.id = o.file and f.name like '%"+file+"%' ";
		}
		if(operation!=null && !operation.equalsIgnoreCase("")){
			hql=hql.concat("and o.operation = '"+operation+"' ");
		}

		if(after!=null && !after.equalsIgnoreCase("")){
			hql=hql.concat("and o.timestamp >= '"+after+"' ");
		}
		if(before!=null && !before.equalsIgnoreCase("")){
			hql=hql.concat("and o.timestamp <= '"+before+"' ");
		}
		if(dspt!=null && !dspt.equalsIgnoreCase("")){
			hql=hql.concat("and o.discription like '%"+dspt+"%'");
		}
		Query query=getSession().createQuery(select+hql);
		query.setFirstResult(start);//定义从第几条开始查询   
        query.setMaxResults(limit);//定义返回的记录数
        List<Privilege> list=query.list();
        
        long totalCount = ((Long) getHibernateTemplate().find("select COUNT(*) "+hql).get(0)).longValue(); 
        ListPage pl=new ListPage(list,(int)totalCount);
		//return (List<Privilege>)getHibernateTemplate().find(hql);
        return pl;

	}
}
